/* eslint-disable */
'use strict'

const express = require('express')
const router = express.Router()
const dbconnection = require('../config/database.js')
const log4js = require('log4js')
const logger = log4js.getLogger('searchConsumer')

const searchConsumerName = (name, flag, callback) => {
  dbconnection.execute('SELECT * FROM infos WHERE name = ? and flag = ?', [name, flag], callback)
}
const searchConsumerMobile = (mobile, flag, callback) => {
  dbconnection.execute('SELECT * FROM infos WHERE mobile = ? and flag = ?', [mobile, flag], callback)
}
const searchConsumer = (flag, callback) => {
  dbconnection.execute('SELECT * FROM infos WHERE flag = ?', flag, callback)
}

/* POST consumer listing. */
router.post('/consumer', (req, res, next) => {
  if (req.session.uuid !== req.cookies.uuid || !req.session.uuid) {
    logger.error(req.session.uuid, req.cookies.uuid)
    return res.send({rtnCode:'302', rtnMsg: '登录过期，请重新登录'});
  }
  switch (req.body.selected) {
    case '姓名':
      searchConsumerName(req.body.search, req.session.flag, (err, results, fields) => {
        if (err) {
          logger.error(err)
          return res.status(500).send({rtnCode: '500', rtnMsg: '服务器错误'})
        }
        results.forEach((e, i) => {
          delete e.flag
        })
        res.send({rtnCode: '000', rtnMsg: '查询成功', contents: results, showPagination: false})
      })
      break;
    case '手机':
      searchConsumerMobile(req.body.search, req.session.flag, (err, results, fields) => {
        if (err) {
          logger.error(err)
          return res.status(500).send({rtnCode: '500', rtnMsg: '服务器错误'})
        }
        results.forEach((e, i) => {
          delete e.flag
        })
        res.send({rtnCode: '000', rtnMsg: '查询成功', contents: results, showPagination: false})
      })
      break;
    default:
      searchConsumer(req.session.flag, (err, results, fields) => {
        if (err) {
          logger.error(err)
          return res.status(500).send({rtnCode: '500', rtnMsg: '服务器错误'})
        }
        results.forEach((e, i) => {
          delete e.flag
        })
        res.send({rtnCode: '000', rtnMsg: '查询成功', contents: results, showPagination: true})
      })
      break;
  }
});

module.exports = router;
